package arrAndstr;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/*
    637. 二叉树的层平均值
    层序遍历
 */
public class T637 {


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> result = new ArrayList<>();

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            Double sum = 0.0;
            int num = queue.size();

            for (int i = 0; i < num; i++) {
                TreeNode node = queue.poll();
                sum += node.val;
                if (node.left != null)  queue.add(node.left);
                if (node.right != null)  queue.add(node.right);
            }

            result.add(sum / num);
        }
        return result;
    }

}
